package com.wm.exam.controller;

import com.wm.exam.common.ServerResponse;
import com.wm.exam.pojo.Category;
import com.wm.exam.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @PostMapping("category/addCategory")
    @ResponseBody
    public ServerResponse addCategory(Category category) {
        // 先根据专业班级查看是否有之前添加的分类
        Category oldCategory = categoryService.getByClazz(category.getClazz());
        if (oldCategory != null) {
            return ServerResponse.createByErrorMessage("您之前添加过该分类试题，请前去删除或者修改");
        }
        String uuid = randomUUID();
        int result = categoryService.insertCategory(category, uuid);
        if (result > 0) {
            return ServerResponse.createBySuccess("添加成功", uuid);
        }
        return ServerResponse.createByErrorMessage("添加失败");
    }

    /**
     * 生成UUID
     */
    public static String randomUUID() {
        Long time = System.currentTimeMillis();
        int random = (int) (Math.random() * 100);
        String uuid = time + random + "";
        return uuid;
    }

    /**
     * 更新分类
     */
    @RequestMapping("category/updateCategory")
    @ResponseBody
    public ServerResponse updateCategory(Category category) {
        // 先根据专业班级查看是否有之前添加的分类
        Category oldCategory = categoryService.getByClazz(category.getClazz());
        if (oldCategory != null) {
            return ServerResponse.createByErrorMessage("您之前添加过该分类试题，请前去删除或者修改");
        }
        // 去数据库更新
        int result = categoryService.updateById(category);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");
    }

    /**
     * 根据UUID删除试题
     */
    @RequestMapping("category/deleteByUUID")
    @ResponseBody
    public ServerResponse deleteByUUID(@RequestParam("uuid") String uuid) {
        int result = categoryService.deleteyUUID(uuid);
        if (result > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

}
